package com.example.widget_lib.widget.taperchart;

import com.example.widget_lib.ResourceTable;
import com.example.widget_lib.bean.TaperChartBean;
import com.example.widget_lib.callback.ScrollObserver;
import com.example.widget_lib.callback.ScrollSubject;
import com.example.widget_lib.utils.LogUtil;
import com.example.widget_lib.utils.PxUtil;
import com.example.widget_lib.utils.Util;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;

import java.util.List;

/**
 * 锥形图容器布局
 */
public class TaperChartLayout extends DirectionalLayout implements TaperChart.DrawDataListener, Component.DrawTask, ScrollObserver {
    private final String TAG = getClass().getSimpleName();
    //数据为空显示的文案
    private static final String NOT_DATA = "暂无统计数据";

    private Context mContext;
    private TaperChart mChart;
    private List<String> mLabels;
    private int DEFAULT_SIZE;
    //文字画笔
    private Paint mTextPaint;
    //测试点
    private Paint mPointPaint;
    //TaperChart设置的间距
    private float mTaperMargin;
    //是否是对比峰值图
    private boolean mIsComparison;

    public TaperChartLayout(Context context) {
        this(context, null);
    }

    public TaperChartLayout(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public TaperChartLayout(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        mContext = context;
        setOrientation(VERTICAL);
        Component component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_taperchart_layout, null, false);
        addComponent(component);
        init(component);
        addDrawTask(this);
//        setEstimateSizeListener(this::onEstimateSize);
    }

    private void init(Component component) {
        mChart = (TaperChart) component.findComponentById(ResourceTable.Id_tchart);
        mChart.setListener(this::onFinish);
        mChart.setNoticeLabel(true);
        setInnerSpace((int) PxUtil.fp2px(28));

        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setColor(new Color(Color.rgb(153, 153, 153)));
        mTextPaint.setTextSize((int) PxUtil.fp2px(10));

        mPointPaint = new Paint();
        mPointPaint.setAntiAlias(true);
        mPointPaint.setStyle(Paint.Style.STROKE_STYLE);
        mPointPaint.setStrokeWidth(12f);
        mPointPaint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);
        mPointPaint.setColor(Color.RED);

        DEFAULT_SIZE = (int) (PxUtil.vp2px(240) + PxUtil.vp2px(20));
        mTaperMargin = PxUtil.vp2px(12);
    }


    /**
     * 设置峰值图颜色值（优先setData之前调用）
     *
     * @param colors
     * @throws IllegalArgumentException TaperChart控件不能为空
     */
    public void setColors(int... colors) {
        if (Util.isEmpty(colors)) {
            return;
        }
        if (Util.isEmpty(mChart)) {
            throw new IllegalArgumentException("TaperChart控件不能为空...");
        }
        mChart.setTaperColors(colors);
    }

    /**
     * 设置图形数据
     *
     * @param xValues
     * @param yValues
     */
    public void setData(List<String> xValues, List<Float> yValues) {
        mIsComparison = false;
        mChart.setData(xValues, yValues);
    }

    /**
     * 设置图形数据
     *
     * @param xValues
     * @param yValues
     * @param labels
     */
    public void setData(List<String> xValues, List<Float> yValues, List<String> labels) {
        mIsComparison = false;
        mChart.setData(xValues, yValues);
        if (Util.isNotEmpty(mLabels)) {
            mLabels.clear();
        }
        mLabels = labels;
    }

    /**
     * 支持点击查看单位
     *
     * @param xValues
     * @param yValues
     * @param labels
     * @param dw
     */
    public void setData(List<String> xValues, List<Float> yValues, List<String> labels, String dw) {
        mIsComparison = false;
        mChart.setData(xValues, yValues, dw);
        if (Util.isNotEmpty(mLabels)) {
            mLabels.clear();
        }
        mLabels = labels;
    }

    /**
     * 设置对比数据
     *
     * @param xValues      x轴标签
     * @param yValues      y轴坐标
     * @param labels       对比的标签组
     * @param dw           单位
     * @param btmLabels    底部括号显示的label标签
     * @param isComparison
     */
    public void setData(List<String> xValues, List<Float> yValues, String[] labels, String dw, List<String> btmLabels, boolean isComparison) {
        mIsComparison = isComparison;
        mChart.setData(xValues, yValues, labels, dw);
        if (Util.isNotEmpty(mLabels)) {
            mLabels.clear();
        }
        mLabels = btmLabels;
    }

    public void setEmpty() {
        if (Util.isNotEmpty(mLabels)) {
            mLabels.clear();
        }
        mChart.setEmpty();
        invalidate();
    }

    public TaperChart getChart() {
        return mChart;
    }

    /**
     * 数据为空的时候，绘制文案
     *
     * @param canvas
     */
    private void drawEmptyData(Canvas canvas) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(new Color(Color.rgb(200, 200, 200)));
        paint.setTextSize((int) PxUtil.fp2px(12f));

        int canvasW = getWidth();
        int canvasH = getHeight();
        int emptyTxtL = Util.getTextWidth(NOT_DATA, paint);
        canvas.drawText(paint, NOT_DATA, canvasW / 2 - emptyTxtL / 2, canvasH / 2 - paint.getStrokeWidth());
    }

    /**
     * 设置Chart交叉距离
     *
     * @param innerSpace
     */
    public void setInnerSpace(int innerSpace) {
        if (mChart != null) {
            mChart.setInnerSpace(innerSpace);
            mChart.invalidate();
        }
    }

    @Override
    public void onFinish() {
        LogUtil.loge(TAG, "onFinish");
        invalidate();
    }

    /*@Override
    public boolean onEstimateSize(int widthEstimateConfig, int heightEstimateConfig) {
        final int width = measureSize(widthEstimateConfig);
        final int height = measureSize(heightEstimateConfig);
        setEstimatedSize(width, height);
        return false;
    }

    private int measureSize(int estimateConfig) {
        int estimateMode = EstimateSpec.getMode(estimateConfig);
        int estimateSize = EstimateSpec.getSize(estimateConfig);
        int result;
        if (estimateMode == EstimateSpec.PRECISE) {//确切大小
            result = (int) (estimateSize + PxUtil.vp2px(20));
        } else {
            //TODO:暂时无效，使用固定值设置测量高度
            result = DEFAULT_SIZE;
        }
        return result;
    }*/

    @Override
    public void onDraw(Component component, Canvas canvas) {
        if (Util.isEmpty(mChart.getList()) || Util.isEmpty(mLabels)) {
//            drawEmptyData(canvas);
            LogUtil.loge(TAG, "清除画布-之前的文案...");
            canvas.drawText(mTextPaint, "", 0, 0);
            return;
        }
        int height = getHeight();
        int topY = getTop();

        LogUtil.loge(TAG, "onDraw parent >>>>>>>> top = " + topY);
        if (mChart != null) {
            mChart.setTopY(mChart.getTopY() + topY);
        }
        LogUtil.loge(TAG, "drawHeight:" + height);
        int size = mLabels.size();
        float halfW = mChart.getLabelW() / 2;
        TaperChartBean bean;

        if (!mIsComparison) { // 绘制底部标签
            LogUtil.loge(TAG, "notmIsComparison");
            for (int i = 0; i < size; i++) {
                bean = mChart.getList().get(i);
                String label = mLabels.get(i);
                float rectFLeft = bean.getRectF().left;
                float x = mTaperMargin + bean.getRectF().left + (halfW - Util.getTextWidth(label, mTextPaint) / 2);
                float y = mChart.getXAxisTxt_Y() + Util.getTextHeight(label, mTextPaint) + PxUtil.vp2px(4);
                LogUtil.loge(TAG, "label:" + label + "rectFLeft:" + rectFLeft + "halfW:" + halfW + "middleTextWidth:" + Util.getTextWidth(label, mTextPaint) / 2);
                canvas.drawText(mTextPaint, label, x, y);
            }
        } else { // 绘制对比形式的底部标签
            LogUtil.loge(TAG, "mIsComparison");
            int innerSize = mChart.getList().size();
            TaperChartBean beanL, beanR;
            for (int i = 0; i < size; i++) {
                float left = 0f;
                float right;
                if (innerSize / 2 == size) {
                    beanL = mChart.getList().get(i * 2);
                    left = beanL.getRectF().left;
                    beanR = mChart.getList().get(i * 2 + 1);
                    right = beanR.getRectF().right;
                    halfW = (right - left) / 2; // 图形的长度要取一组的长度
                }
                String label = mLabels.get(i);
                LogUtil.loge(TAG, label);
                canvas.drawText(mTextPaint, label, mTaperMargin + left + (halfW - Util.getTextWidth(label, mTextPaint) / 2),
                        mChart.getXAxisTxt_Y() + Util.getTextHeight(label, mTextPaint) + PxUtil.vp2px(4));
            }
        }
    }

    @Override
    public void updateScroll(int currentScrollX, int currentScrollY) {
        if (mChart != null) {
            mChart.setCurrentScrollY(currentScrollY);
        }
    }
}
